package com.estate.generator.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.estate.common.utils.fileupload.FileUtil;
import com.estate.generator.service.QiniuService;

import com.estate.system.domain.Buy;
import com.estate.system.service.IBuyService;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.UUID;
@Service
public class QiniuServiceImpl implements QiniuService {
    private static final Logger logger = LoggerFactory.getLogger(QiniuService.class);
    @Resource
    IBuyService iBuyService;
    // 设置好账号的ACCESS_KEY和SECRET_KEY
    String ACCESS_KEY = "M7Yu-AXf3eHllpJe-utuEpMQE8KbKOlUFh_HY3sW";
    String SECRET_KEY = "i1psPrpyJUhn8TyO-DvhMCTPHYpwb2uwFPediOeq";
    // 要上传的空间
    String bucketname = "aifanghome";

    // 密钥配置
    Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
    // 构造一个带指定Zone对象的配置类,不同的七云牛存储区域调用不同的zone
//	Region region = new RegionGroup();
    Configuration cfg = new Configuration(Region.region0());
    // ...其他参数参考类注释
    UploadManager uploadManager = new UploadManager(cfg);

    // 测试域名，只有30天有效期
    private static String QINIU_IMAGE_DOMAIN = "http://www.aifanghome.top/";
    @Override
    // 简单上传，使用默认策略，只需要设置上传的空间名就可以了
    public String getUpToken() {
        return auth.uploadToken(bucketname);
    }
    //已经混有buy对象
    @Deprecated
    @Override
    public String saveBuyImage(MultipartFile file,int uploadId) throws IOException {
        try {
            int dotPos = file.getOriginalFilename().lastIndexOf(".");
            if (dotPos < 0) {
                return null;
            }
            String fileExt = file.getOriginalFilename().substring(dotPos + 1).toLowerCase();
            // 判断是否是合法的文件后缀
            if (!FileUtil.isFileAllowed(fileExt)) {
                return null;
            }
            String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + fileExt;

            // 调用put方法上传
            Response res = uploadManager.put(file.getBytes(), fileName, getUpToken());
            // 打印返回的信息
            if (res.isOK() && res.isJson()) {
                // 返回这张存储照片的地址
                Buy buy=new Buy();
                buy.setImgAddress(QINIU_IMAGE_DOMAIN + JSONObject.parseObject(res.bodyString()).get("key"));
                buy.setId((long) uploadId);
                iBuyService.updateBuy(buy);
                return QINIU_IMAGE_DOMAIN + JSONObject.parseObject(res.bodyString()).get("key");
            } else {
                logger.error("七牛异常:" + res.bodyString());
                return null;
            }
        } catch (QiniuException e) {
            // 请求失败时打印的异常的信息
            logger.error("七牛异常:" + e.getMessage());
            return null;
        }
    }
    //没有混和buy对象,通用上传方法
    //foldName文件夹名
    @Override
    public String saveImageByName(MultipartFile file,String foldName) throws IOException {
        System.out.println("文件名"+foldName);
        System.out.println("------------------上传图片前----------------");
        //判断文件夹名生成路径
        if (foldName!=null){
            foldName=foldName+"/";
        }else {
            foldName="";
        }
        System.out.println("文件夹名"+foldName);
        try {
            int dotPos = file.getOriginalFilename().lastIndexOf(".");
            System.out.println("dotPos"+dotPos);
            if (dotPos < 0) {
                return null;
            }
            System.out.println("next");
            String fileExt = file.getOriginalFilename().substring(dotPos + 1).toLowerCase();
            System.out.println("fileExt"+fileExt);
            // 判断是否是合法的文件后缀
            if (!FileUtil.isFileAllowed(fileExt)) {
                return null;
            }
            System.out.println("后缀合法");
            String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + fileExt;

            fileName=foldName+fileName;
            // 调用put方法上传
            System.out.println("fileName"+fileName);
            Response res = uploadManager.put(file.getBytes(), fileName, getUpToken());
            // 打印返回的信息
            if (res.isOK() && res.isJson()) {
                // 返回这张存储照片的地址

                return QINIU_IMAGE_DOMAIN + JSONObject.parseObject(res.bodyString()).get("key");
            } else {
                logger.error("七牛异常:" + res.bodyString());
                return null;
            }
        } catch (QiniuException e) {
            // 请求失败时打印的异常的信息
            logger.error("七牛异常:" + e.getMessage());
            return null;
        }
    }



    @Override
    public boolean deletePhoto(String fileName,String foldName) {
        //判断文件夹名生成路径
        if (foldName!=null){
            foldName=foldName+"/";
        }else {
            foldName="";
        }
        Configuration configuration = new Configuration(Region.region0());
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        BucketManager bucketManager = new BucketManager(auth, configuration);

        fileName=foldName+fileName;

        try {
            if (fileName != null) {
                bucketManager.delete(bucketname, fileName);
                return true;
            }
        } catch (QiniuException ex) {
            //如果遇到异常，说明删除失败
            logger.error(String.valueOf(ex.code()));
            logger.error(ex.response.toString());
        }
        return false;
    }

}
